import React, { useState, useEffect } from 'react';
import { Table, Button, Input, Pagination, Tabs, Tag, Space, message } from 'antd';
import { SearchOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';
import AddProductModal from '../components/productInWarehouse'; // 产品入库
import ApplyOutProductModal from '../components/apply'; // 申请出库
import ProductEditModal from '../components/editProduct'; // 编辑产品
import ProductAuditModal from '../components/audit'; // 审核
import {
  searchProductForId,
  searchProductForApplyId,
  getProductLength,
  getApplyProductLength,
  returnProductListData,
  returnApplyProductListData,
  deleteProduct,
  withdrawApplyProduct
} from '@/api/product/index';
import { Modal } from 'antd';
import { tracking } from '@/core/utils/operation'


const { TabPane } = Tabs;

const ProductManagement = () => {
  const [activeKey, setActiveKey] = useState('first');
  const [productId, setProductId] = useState(null);
  const [productOutId, setProductOutId] = useState(null);
  const [tableData, setTableData] = useState([]);
  const [applyTableData, setApplyTableData] = useState([]);
  const [paginationData, setPaginationData] = useState({
    productTotal: 0,
    productPageCount: 0,
    productCurrentPage: 1,
    applyProductTotal: 0,
    applyProductCount: 0,
    applyProductCurrentPage: 1,
  });
  // 产品出库
  const [applyItem, setApplyItem] = useState({});
  // 编辑产品
  const [editItem, setEditItem] = useState({});
  // 审核产品
  const [auditItem, setAuditItem] = useState({});
  // 产品入库
  const [AddProductModalVisible, setAddProductModalVisible] = useState(false);
  // 申请出库
  const [ApplyOutProductModalVisible, setApplyOutProductModalVisible] = useState(false);
  // 编辑产品
  const [ProductEditModalVisible, setProductEditModalVisible] = useState(false);
  // 出库审核
  const [ProductAuditModalVisible, setProductAuditModalVisible] = useState(false);
  const name = JSON.parse(localStorage.getItem('userInfo')).name


  // 获取产品列表的总数
  const getProductListLength = async () => {
    const res = await getProductLength();
    setPaginationData((prev) => ({
      ...prev,
      productTotal: res.length,
      productPageCount: Math.ceil(res.length / 10),
    }));
  };

  // 获取审核列表的总数
  const getApplyProductListLength = async () => {
    const res = await getApplyProductLength();
    setPaginationData((prev) => ({
      ...prev,
      applyProductTotal: res.length,
      applyProductCount: Math.ceil(res.length / 10),
    }));
  };

  // 获取产品列表第一页的数据
  const getProductFirstPageList = async () => {
    const data = await returnProductListData(1);
    setTableData(data);
  };

  // 获取审核列表第一页的数据
  const getApplyProductFirstPageList = async () => {
    const data = await returnApplyProductListData(1);
    setApplyTableData(data);
  };

  // 分页切换：产品列表
  const handleProductPageChange = async (page) => {
    setPaginationData((prev) => ({
      ...prev,
      productCurrentPage: page,
    }));
    const data = await returnProductListData(page);
    setTableData(data);
  };

  // 分页切换：申请出库列表
  const handleApplyProductPageChange = async (page) => {
    setPaginationData((prev) => ({
      ...prev,
      applyProductCurrentPage: page,
    }));
    const data = await returnApplyProductListData(page);
    setApplyTableData(data);
  };

  // 搜索：产品
  const searchProduct = async () => {
    const data = await searchProductForId(productId);
    setTableData(data);
  };

  // 搜索：申请出库
  const searchApplyProduct = async () => {
    const data = await searchProductForApplyId(productOutId);
    setApplyTableData(data);
  };

  useEffect(() => {
    if (activeKey === 'first') {
      getProductListLength();
      getProductFirstPageList();
    } else if (activeKey === 'second') {
      getApplyProductListLength();
      getApplyProductFirstPageList();
    }
  }, [activeKey]);

  const handleApply = (record) => {
    setApplyItem(record);
    setApplyOutProductModalVisible(true)
  }

  const handleEditProduct = (record) => {
    setEditItem(record)
    setProductEditModalVisible(true)
  }

  const handleDeleteProduct = (record) => {
    Modal.confirm({
      title: '提示',
      content: '删除后将无法恢复该产品，确定要删除吗',
      okText: '确定',
      cancelText: '取消',
      onOk: async () => {
        const res = await deleteProduct(record.id)
        if (res.status === 0) {
          message.success('删除成功')
          getProductListLength();
          getProductFirstPageList();
        }
      }
    });
  }

  const handleAuditProduct = (record) => {
    setAuditItem(record)
    setProductAuditModalVisible(true)
  }

  const handleWithdrawProduct = (record) => {
    Modal.confirm({
      title: '提示',
      content: '即将撤回该产品出库的申请，确定吗？',
      okText: '确定',
      cancelText: '取消',
      onOk: async () => {
        const res = await withdrawApplyProduct(record.id)
        if (res.status === 0) {
          message.success('撤回成功')
          await tracking('产品', name, record.product_name, '高级', '否决')
          getApplyProductListLength();
          getApplyProductFirstPageList();
        }
      }
    });
  }

  return (
    <div className="module-common-wrapped">
      <div className="module-common-content">
        <Tabs activeKey={activeKey} onTabClick={(key) => setActiveKey(key)}>
          <TabPane tab="产品列表" key="first">
            <div className="pane-content">
              <div className="pane-top">
                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 20 }}>
                  <div className="search-wrapped">
                    <Input
                      value={productId}
                      onChange={(e) => setProductId(e.target.value)}
                      className="w-50 m-2"
                      size="large"
                      placeholder="输入入库编号进行搜索"
                      prefix={<SearchOutlined />}
                      onPressEnter={searchProduct}
                      allowClear
                    />
                  </div>
                  <div className="button-wrapped">
                    <Button type="primary" onClick={() => setAddProductModalVisible(true)}>产品入库</Button>
                  </div>
                </div>
                <Table
                  dataSource={tableData}
                  rowKey="id"
                  bordered
                  pagination={false}
                  columns={[
                    { title: '入库编号', dataIndex: 'product_id', width: 200 },
                    { title: '产品名称', dataIndex: 'product_name', width: 200 },
                    { title: '产品类别', dataIndex: 'product_category', width: 200 },
                    { title: '单位', dataIndex: 'product_unit', width: 200 },
                    { title: '库存数量', dataIndex: 'product_in_warehouse_number', width: 200 },
                    { title: '产品单价', dataIndex: 'product_single_price', width: 200 },
                    { title: '库存总价', dataIndex: 'product_all_price', width: 200 },
                    {
                      title: '库存状态', dataIndex: 'product_status', width: 200,
                      render: (text, row) => {
                        if (row.product_in_warehouse_number < 100) return <Tag color="red">库存较少</Tag>;
                        if (row.product_in_warehouse_number > 100 && row.product_in_warehouse_number < 300) return <Tag color="green">库存正常</Tag>;
                        return <Tag color="orange">库存过剩</Tag>;
                      }
                    },
                    { title: '入库操作人', dataIndex: 'product_create_person', width: 200 },
                    { title: '入库时间', dataIndex: 'product_create_time', width: 200, render: (text) => text ? dayjs(text).format('YYYY-MM-DD HH:mm:ss') : '' },
                    { title: '最后修改时间', dataIndex: 'product_update_time', width: 200, render: (text) => text ? dayjs(text).format('YYYY-MM-DD HH:mm:ss') : '' },
                    { title: '入库备注', dataIndex: 'in_memo', width: 200 },
                    {
                      title: '操作', fixed: 'right', width: 300,
                      render: (text, row) => (
                        <div>
                          <Space direction='vertical'>
                            <a onClick={() => handleApply(row)}>申请出库</a>
                            <a onClick={() => handleEditProduct(row)}>修改</a>
                            <a style={{ color: 'red' }} onClick={() => handleDeleteProduct(row)}>删除</a>
                          </Space>
                        </div>
                      )
                    }
                  ]}
                />
                <div style={{
                  display: 'flex',
                  justifyContent: 'flex-end',
                  marginTop: 20,
                }}>
                  <Pagination
                    current={paginationData.productCurrentPage}
                    total={paginationData.productTotal}
                    pageSize={10}
                    onChange={handleProductPageChange}
                  />
                </div>
              </div>
            </div>
          </TabPane>
          <TabPane tab="审核列表" key="second">
            <div className="pane-content">
              <div className="pane-top">
                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 20 }}>
                  <div className="search-wrapped">
                    <Input
                      value={productOutId}
                      onChange={(e) => setProductOutId(e.target.value)}
                      className="w-50 m-2"
                      size="large"
                      placeholder="输入申请出库编号进行搜索"
                      prefix={<SearchOutlined />}
                      onPressEnter={searchApplyProduct}
                      allowClear
                    />
                  </div>
                </div>
                <Table
                  dataSource={applyTableData}
                  rowKey="id"
                  bordered
                  pagination={false}
                  columns={[
                    { title: '申请出库编号', dataIndex: 'product_out_id', width: 200 },
                    { title: '产品名称', dataIndex: 'product_name', width: 200 },
                    { title: '申请出库数量', dataIndex: 'product_out_number', width: 200 },
                    { title: '申请出库总价', dataIndex: 'product_out_price', width: 200 },
                    { title: '申请人', dataIndex: 'product_out_apply_person', width: 200 },
                    { title: '申请出库时间', dataIndex: 'product_apply_time', width: 200, render: (text) => text ? dayjs(text).format('YYYY-MM-DD HH:mm:ss') : '' },
                    { title: '审核人', dataIndex: 'product_out_audit_person', width: 200 },
                    { title: '审核时间', dataIndex: 'product_audit_time', width: 200, render: (text) => text ? dayjs(text).format('YYYY-MM-DD HH:mm:ss') : '' },
                    { title: '审核状态', dataIndex: 'product_out_status', width: 200 },
                    { title: '申请出库备注', dataIndex: 'apply_memo', width: 200 },
                    { title: '审核备注', dataIndex: 'audit_memo', width: 200 },
                    {
                      title: '操作', fixed: 'right', width: 300,
                      render: (text, row) => (
                        <div>
                          <Space direction='vertical'>
                            <a onClick={() => handleAuditProduct(row)}>审核</a>
                            <a style={{ color: 'red' }} onClick={() => handleWithdrawProduct(row)}>撤回申请</a>
                          </Space>
                        </div>
                      )
                    }
                  ]}
                />
                <div style={{
                  display: 'flex',
                  justifyContent: 'flex-end',
                  marginTop: 20,
                }}>
                  <Pagination
                    current={paginationData.applyProductCurrentPage}
                    total={paginationData.applyProductTotal}
                    pageSize={10}
                    onChange={handleApplyProductPageChange}
                  />
                </div>
              </div>
            </div>
          </TabPane>
        </Tabs>
      </div>

      {/* 以下是其他弹出组件 */}
      <AddProductModal visible={AddProductModalVisible} onClose={() => setAddProductModalVisible(false)} onSuccess={() => getProductFirstPageList()} />
      <ApplyOutProductModal visible={ApplyOutProductModalVisible} item={applyItem} onClose={() => setApplyOutProductModalVisible(false)} onSuccess={() => getProductFirstPageList()} />
      <ProductEditModal visible={ProductEditModalVisible} item={editItem} onClose={() => setProductEditModalVisible(false)} onSuccess={() => getProductFirstPageList()} />
      {/* 审核列表操作弹窗 */}
      <ProductAuditModal visible={ProductAuditModalVisible} item={auditItem} onClose={() => setProductAuditModalVisible(false)} onSuccess={() => getApplyProductFirstPageList()} />
    </div>
  );
};

export default ProductManagement;
